﻿using System.Collections;
using System.Configuration;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Linq;

namespace Jiubang.Authentications.Permissions {
    /// <summary>
    /// 默认权限验证方式。采用数据表保存用户组权限。<br/>
    /// </summary>
    public sealed class DbPermission<T> : IPermission where T : class, IDbPermissionInfo {
        private readonly string conn;
        private readonly bool denyAsDefault;

        /// <param name="connectionName">在connections节点中的数据库连接名称</param>
        /// <param name="denyAsDefault">权限表中未指定的项目是否默认为拒绝</param>
        public DbPermission(string connectionName,bool denyAsDefault) {
            conn = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            this.denyAsDefault = denyAsDefault;
        }

        #region IPermission Members

        /// <summary>
        /// 请求动作执行权限
        /// </summary>
        /// <param name="session">用户会话</param>
        /// <param name="path">请求路径</param>
        /// <param name="access">动作名称</param>
        /// <returns>允许时返回True</returns>
        public bool Ask(UserSession session, string path, string access) {
            using (var context = new DataContext(new SqlConnection(conn))) {
                var permissionInfo = context.GetTable<T>().SingleOrDefault(c => c.Action == access && c.Path == path);

                //未添加权限时默认为拒绝
                if (permissionInfo == null)
                    return !denyAsDefault;

                return new BitArray(permissionInfo.DepartmentCode).Get(session.DepartmentCode - 1)
                       && new BitArray(permissionInfo.RoleCode).Get(session.RoleCode - 1);
            }
        }

        #endregion
    }
}